import { Module, Store } from "vuex";
import { UserService, Account } from "@/api/user";
import Code from "@/consts/common";
const createModule = <S, R>(store: Module<S, R>) => store as Store<S>;
//https://zhuanlan.zhihu.com/p/143884250
interface UserState {
  total: number;
  loading: boolean;
  userList: Account[];
  page: number;
  size: number;
}

let userState: UserState = {
  total: 0,
  loading: false,
  userList: [],
  page: 1,
  size: 15,
};
// 定义一个 module
export default createModule({
  namespaced: true,
  state: userState,
  actions: {
    getUserList({ commit }, params: any) {
      commit("changeLoading");
      UserService.userList(params).then((res) => {
        if (res.code == Code.CODE_SUCCESS) {
          commit("getUserList", res.data);
        }
        commit("changeLoading");
      });
    },
    pageChange({ commit, dispatch }, data: any) {
      commit("pageChange", data.page);
      dispatch("getUserList", data);
    },
    pageSizeChange({ commit, dispatch }, data: any) {
      commit("pageSizeChange", data.size);
      dispatch("getUserList", data);
    },
    addAfterLoadUserList({ commit }, params: any) {
      UserService.userList(params).then((res) => {
        if (res.code == Code.CODE_SUCCESS) {
          commit("getUserList", res.data);
        }
      });
    },
  },
  mutations: {
    saveUserToLoc(state, data) {
      localStorage.setItem("userId", data.userId);
      localStorage.setItem("token", data.token);
    },
    getUserList(state, data) {
      state.total = data.total;
      state.userList = data.data;
    },
    pageChange(state, page) {
      state.page = page;
    },
    changeLoading(state) {
      state.loading = !state.loading;
    },
    pageSizeChange(state, pageSize) {
      state.size = pageSize;
    },
  },
});
